package com.golxen.framework.common;

import com.golxen.framework.ClientProtocol;
import com.golxen.framework.CrossProtocol;
import com.golxen.framework.GameErrorCode;
import com.golxen.framework.GameProtocol;
import com.golxen.framework.common.server.game.cmd.CommandSet;
import sun.plugin2.main.server.AbstractPlugin;

import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;

public class CommandPlugin {

    static CommandPlugin instance = null;

    public static void start() {
        if (instance != null) {
            return;
        }

        instance = new CommandPlugin();

        checkDuplicate(GameErrorCode.class);
        checkDuplicate(ClientProtocol.class);
        checkDuplicate(CrossProtocol.class);
        checkDuplicate(GameProtocol.class);

        CommandSet.load();
    }

    public static boolean active() {
        return instance != null;
    }

    private static void checkDuplicate(Class<?> clazz) {
        Field[] declaredFields = clazz.getDeclaredFields();
        Set<Integer> errorCodeSet = new HashSet<>();
        Set<Integer> duplicateErrorCodeSet = new HashSet<>();
        for (Field field : declaredFields) {
            try {
                Object aShort = field.get(clazz);
                int value = Integer.parseInt(aShort.toString());
                if (errorCodeSet.contains(value)) {
                    duplicateErrorCodeSet.add(value);
                }
                errorCodeSet.add(value);
            } catch (IllegalAccessException e) {
                throw new RuntimeException("check Code error: " + clazz.getSimpleName());
            }
        }
        if (duplicateErrorCodeSet.size() > 0) {
            System.err.println(duplicateErrorCodeSet);
            throw new RuntimeException("code duplicate:  " + clazz.getSimpleName() + "      " + duplicateErrorCodeSet);
        }
    }

}
